# -*- coding: utf-8 -*-
# @Time    : 2019/2/20 11:53
# @Author  : fovegage
# @Email   : fovegage@gmail.com
# @File    : tets.py
# @Software: PyCharm

import tornado.web
import tornado.httpserver
import tornado.ioloop
from tornado_api.api import one, random
import hashlib
import time
import sys
import xmltodict

class WechatHandler(tornado.web.RequestHandler):
    def get(self):
        signature = self.get_argument("signature", "")
        timestamp = self.get_argument("timestamp", "")
        nonce = self.get_argument("nonce", "")
        echostr = self.get_argument("echostr", "")
        tmp = ['fovegage', timestamp, nonce]
        tmp.sort()
        tmp = "".join(tmp)
        s1 = hashlib.sha1()
        s1.update(tmp.encode())
        tmp = s1.hexdigest()
        if tmp == signature:
            self.write(echostr)
        else:
            self.write("非微信请求，拒绝访问!!!")

    def post(self):

        req_xml = self.request.body
        print(req_xml)
        req = xmltodict.parse(req_xml)['xml']
        print(req.get("MsgType"))
        if "text" == req.get("MsgType"):
            resp = {
                "ToUserName":req.get("FromUserName", ""),
                "FromUserName":req.get("ToUserName", ""),
                "CreateTime":int(time.time()),
                "MsgType":"text",
                "Content":req.get("Content", ""),
                "MsgId": req.get("MsgId", "")
            }
        else:
            resp = {
                "ToUserName":req.get("FromUserName", ""),
                "FromUserName":req.get("ToUserName", ""),
                "CreateTime":int(time.time()),
                "MsgType":"text",
                "Content":"I love you, itcast!",
                "MsgId": req.get("MsgId", "")
            }
        resp_xml = xmltodict.unparse({"xml":resp})
        self.write(resp_xml)

if __name__ == '__main__':
    app = tornado.web.Application(
        handlers=[
            (r'/',WechatHandler),
        ],

    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(7261)
    tornado.ioloop.IOLoop.instance().start()
